<template>
   <div>
     <web-view v-if="webViewSrc" :src="webViewSrc" @message="postMessage"></web-view>
   </div>
</template>

<script>
import { H5_URL } from "@/global";
import crypto from 'crypto-js';
import { Base64 } from 'js-base64';
import {getOSS} from "../../api";

// 计算签名。
function computeSignature(accessKeySecret, canonicalString) {
  return crypto.enc.Base64.stringify(crypto.HmacSHA1(canonicalString, accessKeySecret));
}

const date = new Date();
date.setHours(date.getHours() + 1);
const policyText = {
  expiration: date.toISOString(), // 设置policy过期时间。
  conditions: [
    // 限制上传大小。
    ["content-length-range", 0, 1024 * 1024 * 1024],
  ],
};

async function getFormDataParams() {
  const res = await getOSS()
    const credentials = res.data
    console.log('credentials',credentials)
  const policy = Base64.encode(JSON.stringify(policyText)) // policy必须为base64的string。
    console.log('policy',policy)
  const signature = computeSignature(credentials.accessKeySecret, policy)
  const formData = {
    OSSAccessKeyId: credentials.accessKeyId,
    signature,
    policy,
    'x-oss-security-token': credentials.securityToken
  }
  return formData
}
export default {
    name: "create",
    data() {
        return {
            webViewSrc: '',
          aimgurl: "", // //临时图片的路径
          countIndex: 1, // 可选图片剩余的数量
          imageData: [], // 所选上传的图片数据
            options: {},
            cardId: ''
        }
    },
    onLoad(options) {
        this.cardId = options.id
        wx.setStorageSync('systemInfo',  wx.getSystemInfoSync() ? {
            screenWidth: wx.getSystemInfoSync().safeArea.width,
            screenHeight: wx.getSystemInfoSync().safeArea.height,
        } : {screenWidth: 350,screenHeight: 750 })
        this.webViewSrc = `${H5_URL}edit-desgin?screenWidth=${wx.getStorageSync('systemInfo').screenWidth}&screenHeight=${wx.getStorageSync('systemInfo').screenHeight}&token=${wx.getStorageSync('token')}&id=${options.id}&UPLOAD_FILE=${options.UPLOAD_FILE || ''}&time=${new Date().getTime()}`
    },
    methods: {
      postMessage(e) {
        console.log(e)
        if (e.detail.data[0].action === 'image') {
            this.cardId = e.detail.data[0].cardId
            console.log('this.cardId',this.cardId)
            this.browse()
        }
      },/*图片浏览及上传 */
      browse() {
        let that = this;
        wx.showActionSheet({
          itemList: ['从相册中选择', '拍照'],
          itemColor: "#000",
          success: function(res) {
            if (!res.cancel) {
              if (res.tapIndex == 0) {
                that.chooseWxImage('album');
              } else if (res.tapIndex == 1) {
                that.chooseWxImage('camera');
              }
            }
          }
        })
      },
      /*打开相册、相机 */
      chooseWxImage(type) {
        let that = this;
        wx.chooseImage({
          count: that.countIndex,
          sizeType: ['original', 'compressed'],
          sourceType: [type],
          success: function(res) {
            // 选择图片后的完成确认操作
            that.aimgurl = res.tempFilePaths[0]
            that.upLoadImgFun(res.tempFilePaths[0])
          }
        })
      },
      /**上传：图片到服务器 */
      async upLoadImgFun(filePath) {
        const formData = await getFormDataParams()
        const host = 'https://hekas.oss-cn-hangzhou.aliyuncs.com';
          const key = 'images/' + filePath.split('://')[1]
          const fullPath = host + '/' + key
        wx.uploadFile({
          url: host, // 开发者服务器的URL。
          filePath: filePath,
          name: 'file', // 必须填file。
          formData: {
            ...formData,
            key,
          },
          success: (res) => {
            if (res.statusCode === 204) {
              console.log('上传成功',fullPath);
                uni.redirectTo({
                    url: `/pages/desgin/edit?id=${this.cardId}&UPLOAD_FILE=${fullPath}`,
                })
            }
          },
          fail: err => {
            console.log(err);
          }
        });
      }
    }
}
</script>

<style lang="less">
</style>
